package com.shop.shopserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shop.shopcommon.constant.MessageConstant;
import com.shop.shopcommon.exception.Base.OrderException;
import com.shop.shopcommon.result.Result;
import com.shop.shoppojo.dto.StockTotalDTO;
import com.shop.shoppojo.entity.Goods;
import com.shop.shoppojo.vo.StockTotalVO;
import com.shop.shopserver.mapper.StockTotalMapper;
import com.shop.shopserver.service.StockTotalService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class StockTotalServiceImpl extends ServiceImpl<StockTotalMapper, Goods> implements StockTotalService {

    @Autowired
    private StockTotalMapper stockTotalMapper;

    @Transactional(propagation = Propagation.REQUIRED)
    public Result<StockTotalVO> updateStockTotal(StockTotalDTO stockTotalDTO) {
        Goods goods = getOne(new LambdaQueryWrapper<Goods>().eq(Goods::getId, stockTotalDTO.getGoodsId()));
        if (goods == null){
            throw new OrderException(MessageConstant.GOODS_IS_NUM);
        }
        if (goods.getStockTotal() < stockTotalDTO.getGoodsNum()){
            throw new OrderException(MessageConstant.STOCK_TOTAL_IS_NULL);
        }
        goods.setStockTotal(goods.getStockTotal() - stockTotalDTO.getGoodsNum());
        goods.setGoodsSales(goods.getGoodsSales() + stockTotalDTO.getGoodsNum());
        stockTotalMapper.update(goods, new LambdaQueryWrapper<Goods>().eq(Goods::getId, stockTotalDTO.getGoodsId()));

        StockTotalVO stockTotalVO = new StockTotalVO();
        BeanUtils.copyProperties(goods, stockTotalVO);
        return Result.success(stockTotalVO, "更新成功");
    }
}
